<?php

namespace App\Http\Controllers\Wechat\Plugins;

use Laravel\Lumen\Routing\Controller as BaseController;
use Xu42\Cet\CetScore as Cet;
use App\Http\Controllers\Wechat\Messages;
use Illuminate\Http\Request;

class CetScore extends BaseController
{
    public static function get($message)
    {
        preg_match('/([\x{4e00}-\x{9fa5}]+)/u', $message->Content, $username);
        preg_match('/(\d+)/', $message->Content, $number);

        $score = (new Cet())->get($number[1], $username[1]);

        if (is_null($score)) {
            return Messages\Text::wrongCetQuery();
        }

        $detail = sprintf('笔试：\n总分%s 听力%s 阅读%s 写作和翻译%s\n口试：等级 %s', $score['written']['score'], $score['written']['listening'], $score['written']['reading'], $score['written']['translation'], $score['oral'['score']]);

        $remark = '很遗憾，没有通过四六级考试';
        if ($score['written']['score'] >= 425) {
            $remark = '恭喜你通过了四六级考试！';
        }

        Messages\Notices::cet($message->FromUserName, $score['name'], $score['school'], $score['number'], $detail, $remark);
    }


    /**
     * 网页 cet查询
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public static function cetPost(Request $request)
    {
        $name   = $request->get('name');
        $number = $request->get('number');

        if (is_null($name) || is_null($number)) {
            return view('wechat.cet');
        }

        $cetScore = (new Cet())->get($number, $name);
        $queryRes = is_null($cetScore) ? false : true;

        $app      = new \EasyWeChat\Foundation\Application(config('wechat'));
        $jsConfig = $app->js->config([
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareQZone'
        ], false);

        return view('wechat.cetres')->with('score', $cetScore)->with('query', $queryRes)->with('name', $name)->with('jsconfig', $jsConfig);
    }
}